//
//  PopoverPresentationController.swift
//  SinaWeibo
//
//  Created by 胡阳 on 16/5/20.
//  Copyright © 2016年 young4ever. All rights reserved.
//

import UIKit

class PopoverPresentationController: UIPresentationController {
    
    var presentFrame:CGRect = CGRectZero

    /**
     初始化方法,用于创建负责转场动画的对象
     
     - parameter presentedViewController:  被展现的控制器
     - parameter presentingViewController: 发起转场的控制器<Xcode6为nil,Xcode7为野指针>
     
     - returns: 负责转场动画的对象
     */
    override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
     
        super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
    }
    
    /**
     即将布局转场子视图时候调用
     */
    override func containerViewWillLayoutSubviews() {
        
        //1.修改弹出视图的大小
        
        if presentFrame == CGRectZero {
            let height = UIScreen.mainScreen().bounds.size.height - 200
            presentedView()?.frame = CGRect(x: 100, y: 56, width: 200, height: height)
        }else {
            presentedView()?.frame = presentFrame 
        }
        
        //2.在容器视图上插入一个蒙版view
        containerView?.addSubview(coverView)
        containerView?.bringSubviewToFront(presentedView()!)
    }
    
    // MARK:- 懒加载一个蒙版view
    private lazy var coverView: UIView = {
    
        let view = UIView()
        view.frame = UIScreen.mainScreen().bounds
        view.backgroundColor = UIColor(white: 0.0, alpha: 0.2)
        view.userInteractionEnabled = true
        let tapGes = UITapGestureRecognizer(target: self, action: #selector(PopoverPresentationController.tapToClose))
        view.addGestureRecognizer(tapGes)
        return view
    }()
    
    /**
     点击蒙版使得弹出视图消失
     */
    func tapToClose() {
        
        presentedViewController.dismissViewControllerAnimated(true, completion: nil)
    }
}
